# 开启服务可以使用web形式浏览报告,不需要打开文件

import os
from flask import Flask,render_template
# 导入基类转换器
from werkzeug.routing import BaseConverter


DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


app = Flask(__name__)


# 1.自定义类,继承自BaseConverter
class MyRegexConverter(BaseConverter):
    # 2.编写初始化方法, init方法, 接收两个参数, url_map, regex, 并初始化父类空间和子类空间
    def __init__(self, url_map, regex):
        super(MyRegexConverter, self).__init__(url_map)
        self.regex = regex


# 3.将自定义转换器类,添加到默认的转换列表中
app.url_map.converters['re'] = MyRegexConverter


# 使用自定义转换器
@app.route('/<re("autotest/report/.*"):file>')
def show_report(file):
    file_path = os.path.join(os.path.dirname(DIR),file)

    with open(file_path,encoding="utf-8") as f:
        return f.read()


@app.route('/')
def index():
    report_dir = os.path.join(DIR,"report")
    l = os.listdir(report_dir)
    res = []

    # 最多显示20条
    last = 20 if len(l) >20 else len(l)
    for i in l[:-last:-1]:
        path = "/autotest/report/{}/index.html".format(i)
        tmp = '<p style="padding-left: 5%;margin: 5px 0"><a href="{}" target="_blank">{}</a></p>'.format(path,i)
        res.append(tmp)

    return "".join(res)


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000)